package client.comm.baoding.ui.vm

import android.app.Application
import android.net.Uri
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.comm.baoding.api.bean.UploadRet
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.network.data.Ret
import client.comm.commlib.out_time
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.StoreUtil
import client.comm.commlib.utils.Util
import client.comm.baoding.ui.viewmodel.MiddleVm
import client.comm.baoding.api.bean.UserInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Response

class TiShuiViewModel(app: Application) : MiddleVm(app) {
    val call = MutableLiveData<JsonResult<Ret>>()
    val isShowing = MutableLiveData<Boolean>()
    val txType = MutableLiveData<Int>(-1)
    val smscode = MutableLiveData<String>("")
    val getCodeTxt = MutableLiveData<String>("获取验证码")
    val getCodeEnable = MutableLiveData<Boolean>(true)
    val txNum = MutableLiveData<String>()
    val codeRet = MutableLiveData<JsonResult<Ret>>()

    val userInfo = MutableLiveData<UserInfo>()
    val imgOne = MutableLiveData<Uri>()


    fun checkZfb() {
        txType.value = 1
    }

    fun checkWx() {
        txType.value = 2
    }

    fun checkBank() {
        txType.value = 3
    }

    /**
     */
    fun ok(owner: LifecycleOwner) {
        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<UploadRet>>? = null
                val file = Util.getLuBan(
                    owner,
                    this@TiShuiViewModel.imgOne.value!!
                )
                val requestFile: RequestBody = RequestBody.create(
                    "multipart/form-data".toMediaTypeOrNull(),
                    file
                )
                val body = MultipartBody.Part.createFormData(
                    "file",
                    file.name,
                    requestFile
                )
                val descriptionString = "file"
                val description = RequestBody.create(
                    "multipart/form-data".toMediaTypeOrNull(),
                    descriptionString
                )
                out_time {
                    val ret = server.upload(description, body)
                    emm = ret
                }

//                var emm: Response<JsonResult<Ret>>? = null
//                out_time {
//                    val ret = server.validatePayPwd(it)
//                    emm = ret
//                }

                emit(emm)
            }.map {
                var emm: Response<JsonResult<Ret>>? = null
                it?.body()?.let {
                    if (it.isSuccess) {
                        var payType = "1"
                        when (txType.value) {
                            1 -> {
                                payType = "1"
                            }
                            2 -> {
                                payType = "2"
                            }
                            3 -> {
                                payType = "3"
                            }
                        }
                        out_time {
                            val ret = server.tx2(
                                txNum.value!!,
                                "2",
                                payType,
                                smscode.value!!,
                                userInfo.value!!.phone,
                                it.data!!.url,
                            )
                            emm = ret
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO)
                .onCompletion {
                    isShowing.value = false
                }.catch { cause ->
                    if (cause != null) {
//                        toast(cause.message)
                        toast("网络错误")
                    }
                }.collectLatest {
                    call.value = it?.body()
//                    okCall.value = it?.body()
                }
        }
    }

    fun getCode() {
        hold({
            val ts = System.currentTimeMillis()
            val user = StoreUtil.getBean<UserInfo>(getApplication())
            server.getcode(
                user!!.phone,
                "${ts}", Util.getCaptchaSign(user!!.phone, "${ts}")
            )
        }, {
            isShowing.value = true
            getCodeEnable.value = false
            codeRet.value = null
        }, {
            codeRet.value = it
        }, complete = {
            isShowing.value = false
        }, err = {
            getCodeEnable.value = true
        })

    }

    fun cancle() {

    }

}